﻿#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent) :
    BaseEditor(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);

    table=TD_RAL;
    convertTable=TD_PANTONG;
    model=new QSqlTableModel(this);
    // model->setEditStrategy(QSqlTableModel::OnManualSubmit);
    ui->tableView->setModel(model);
    ui->tableView->setEditTriggers(QTableView::NoEditTriggers);

    updateView();
    createMenu();
    loadLocation();
}

Widget::~Widget()
{
    saveLocation();
    delete ui;
}

void Widget::generateMenu()
{
    menu->addAction(QStringLiteral("更新"),this,&Widget::updateView);
}

void Widget::updateView()
{
    model->setTable(table);
    model->select();

    ui->tableView->hideColumn(0);   //id
    model->setHeaderData(1,Qt::Horizontal,QStringLiteral("RAL编号")); //label
    model->setHeaderData(2,Qt::Horizontal,QStringLiteral("中文名"));
    model->setHeaderData(3,Qt::Horizontal,QStringLiteral("英文名"));
    ui->tableView->hideColumn(4);   //rval
    ui->tableView->hideColumn(5);   //gval
    ui->tableView->hideColumn(6);   //bval
}

void Widget::on_search_returnPressed()
{
    QString keyword=ui->search->text().trimmed();
    if(keyword.isEmpty())
        return;

    showSearchBox(keyword);
}

void Widget::showSearchBox(const QString &keyword)
{
    model->setFilter(QString("label like '%%1%' OR name_cn like '%%1%'").arg(keyword));
    model->select();
}

void Widget::drawColor(const QColor &color)
{
    QPicture picture;
    QPainter painter;
    painter.begin(&picture);
    QBrush brush(color);
    painter.setBrush(brush);
    painter.drawRect(0,0,384,240);
    painter.end();
    ui->canva->setPicture(picture);
}

void Widget::on_btn_clean_clicked()
{
    ui->search->clear();
}

void Widget::on_tableView_doubleClicked(const QModelIndex &index)
{
    if(index.isValid())
    {
        selectLabel=index.sibling(index.row(),1).data().toString();
        int rval=index.sibling(index.row(),4).data().toInt();
        int gval=index.sibling(index.row(),5).data().toInt();
        int bval=index.sibling(index.row(),6).data().toInt();
        drawColor(QColor(rval,gval,bval));

        QString summary=selectLabel + "\n"
                + QString("RGB(")
                + QString::number(rval) + QString(",")
                + QString::number(gval) + QString(",")
                + QString::number(bval) + QString(")");
        ui->summary->setText(summary);
    }
    ui->pantong->clear();
}

void Widget::on_btn_convert_clicked()
{
    if(selectLabel.isEmpty())
        return;

    QSqlQuery query;
    query.exec(QString("select detail from %1 where label='%2'")
               .arg(convertTable)
               .arg(selectLabel));
    if(query.next())
        ui->pantong->setText(query.value(0).toString());
    else
        ui->pantong->setText(QStringLiteral("找不到对应颜色值"));
}
